package 力扣._543_二叉树的直径;

import 力扣.公用数据结构.TreeNode;

public class Solution {
    //当前子树最大深度
    int maxdeepth(TreeNode root) {
        if (root == null)
            return 0;
        return Math.max(maxdeepth(root.left), maxdeepth(root.right)) + 1;

    }

    //对每个节点使用maxdeepth找到最大
    int max = 0;

    void max(TreeNode root) {
        if (root == null)
            return;
        int now_l = maxdeepth(root.left);
        int now_r = maxdeepth(root.right);
        int now = now_l + now_r;
        max = Math.max(max, now);
        if(now_l>now/2)
            max(root.left);
        if(now_r>now/2)
            max(root.right);
    }

    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null)
            return 0;
        max(root);
        return max;
    }

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);
        node1.left = node2;
        node1.right=node3;
        node2.left=node4;
        node2.right=node5;
        int i = new Solution().diameterOfBinaryTree(node1);
        System.out.println(i);

    }
}
